package com.xinchao.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xinchao.core.BaseController;
import com.xinchao.core.constant.BusinessConstant;
import com.xinchao.core.constant.RequestConstant;
import com.xinchao.core.constant.ResponseConstant;
import com.xinchao.core.exception.ControllerException;
import com.xinchao.core.util.HttpUtils;
import com.xinchao.model.DeviceUpgrade;
import com.xinchao.model.User;
import com.xinchao.model.dto.AreaDistrictDTO;
import com.xinchao.model.dto.DeviceModelDTO;
import com.xinchao.model.page.PageInfo;
import com.xinchao.model.sys.JsonResponse;
import com.xinchao.model.vo.DeviceUpgradeListVO;
import com.xinchao.model.vo.DeviceUpgradeVO;
import com.xinchao.model.vo.UpgradeDeviceListVO;
import com.xinchao.service.AreaService;
import com.xinchao.service.DeviceInfoService;
import com.xinchao.service.DeviceModelService;
import com.xinchao.service.UpgradeService;
import net.dongliu.apk.parser.exception.ParserException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SoftwareUpgradeController
 * @Description 软件（APK）升级
 * @Author HanQinrui
 * @Date 2018/8/13 17:39
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "/software")
public class SoftwareUpgradeController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(SoftwareUpgradeController.class);
	@Autowired
	private UpgradeService deviceUpgradeService;
	@Autowired
	private DeviceModelService deviceModelService;
	@Autowired
	private DeviceInfoService deviceInfoService;
	@Autowired
	private AreaService areaService;

	/**
	 * apk管理分页列表
	 * hanqr 2018-08-13
	 * @param modelView 模型
	 * @param pageNum 当前页
	 * @param pageSize 每页条数
	 * @return
	 */
	@RequestMapping(value = "/listByPage")
	public Object apkListByPage( Model modelView, Integer pageNum, Integer pageSize, HttpServletRequest request) {
		try {
			// 获取用户信息
			User user = getSessionUser(request);
			if(user == null) {
				return new ControllerException("用户名为空，请联系管理员");
			}
			PageInfo<DeviceUpgradeListVO> pageInfo = deviceUpgradeService.listDeviceUpgradeByPage(BusinessConstant.DEVICE_UPGRADE_TYPE_SOFTWARE, pageNum, pageSize);
			modelView.addAttribute("apkList", pageInfo.getList());
			modelView.addAttribute("total", pageInfo.getTotal());
			modelView.addAttribute("pageNum", pageInfo.getPageNum());
			modelView.addAttribute("pageSize", pageInfo.getPageSize());
		} catch (Exception e) {
			logger.error("SoftwareUpgradeController apkListByPage 获取apk列表失败：" + e.getMessage(),e);
		}
		return "software_upgrade_list";
	}

	/**
	 * 跳转至新增apk界面
	 * hanqr 2018-08-14
	 * @param model 模型
	 * @return
	 */
	@RequestMapping(value = "/goAddApk")
	public String goAddApk(Model model){
		// 获取终端型号列表
		List<DeviceModelDTO> deviceModelList = deviceModelService.listDeviceModels();
		model.addAttribute("deviceModelList", deviceModelList);
		return "software_upgrade_add";
	}

	/**
	 * apk文件上传
	 * hanqr 2018-08-14
	 * @param files apk文件
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/upload/apk", method = RequestMethod.POST)
	public Object uploadAPKFile(@RequestParam("files") MultipartFile files) {
		if (files == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "上传文件不能为空");
		} else if (files.getSize() <= 0) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "文件内容不能为空");
		}
		String fileName = files.getOriginalFilename();
		if (StringUtils.isBlank(fileName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "文件名不能为空");
		}
		if (!fileName.endsWith(BusinessConstant.FILE_SUFFIX_APK)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "文件格式不对！");
		}
		try {
			List<Map<Object,Object>> msgList = Lists.newArrayList();
			Map<Object, Object> msgMap = deviceUpgradeService.saveApkFile(files);
			msgList.add(msgMap);
			return msgList;
		} catch (ParserException e) {
			logger.error("SoftwareUpgradeController uploadFile apk上传文件失败：" + e.getMessage(),e);
			return new JsonResponse(ResponseConstant.CODE_FAIL, "获取apk文件信息有误，请检查apk是否正确！");
		} catch (IOException e) {
			logger.error("SoftwareUpgradeController uploadFile apk上传文件失败：" + e.getMessage(),e);
			return new ControllerException("apk上传文件失败");
		}
	}

	/**
	 * 保存apk
	 * hanqr 2018-08-14
	 * @param deviceUpgrade
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveApk")
	public Object saveApk(DeviceUpgrade deviceUpgrade, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		//验证参数
		if (deviceUpgrade == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		//验证参数
		if (StringUtils.isBlank(deviceUpgrade.getUpgradeName()) || StringUtils.isBlank(deviceUpgrade.getModelId())
				|| StringUtils.isBlank(deviceUpgrade.getUrl())|| deviceUpgrade.getVersionCode() == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		try {
			deviceUpgrade.setUpgradeType(BusinessConstant.DEVICE_UPGRADE_TYPE_SOFTWARE);
			deviceUpgradeService.saveDeviceUpgrade(deviceUpgrade, user, HttpUtils.getRemortIP(request));
		} catch (Exception e) {
			logger.error("SoftwareUpgradeController saveApk 保存终端升级信息失败：" + e.getMessage(),e);
			return new JsonResponse(ResponseConstant.CODE_FAIL,"保存终端升级信息失败");
		}
		return "";
	}

	/**
	 * 跳转至升级APK
	 * hanqr 2018-08-14
	 * @param request
	 * @param deviceUpgradeId apk主键
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/goUpgradeApk")
	public Object goUpgradeApk(HttpServletRequest request,Long deviceUpgradeId, Model model) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if (deviceUpgradeId == null) {
			logger.error("SoftwareUpgradeController goUpgradeApk 参数为空，请联系管理员" );
		}
		try {
			// 获取机型列表
			List<DeviceModelDTO> deviceModelList = deviceModelService.listDeviceModels();
			model.addAttribute("deviceModelList", deviceModelList);
			// 获取固件升级实体对象
			DeviceUpgradeVO deviceUpgradeVO = deviceUpgradeService.getDeviceUpgradeByIdVo(deviceUpgradeId);
			model.addAttribute("deviceUpgrade", deviceUpgradeVO);
		} catch (Exception e) {
			logger.error("SoftwareUpgradeController goUpgradeApk 升级APK：" + e.getMessage(),e);
		}
		return "software_upgrade_update";
	}


	/**
	 * 升级APK
	 * hanqr 2018-08-14
	 * @param deviceUpgrade 终端更新对象
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/upgradeApk", method = RequestMethod.POST)
	public Object upgradeApk(DeviceUpgrade deviceUpgrade,  HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		Long deviceUpgradeId = deviceUpgrade.getDeviceUpgradeId();
		if (deviceUpgradeId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "升级ID为空，请联系管理员");
		}
		try {
			deviceUpgradeService.updateDeviceUpgrade(deviceUpgrade, user,HttpUtils.getRemortIP(request));
		} catch (Exception e) {
			logger.error("SoftwareUpgradeController upgradeApk升级APK：" + e.getMessage(),e);
			return e;
		}
		return "";

	}

	/**
	 * apk-终端列表信息
	 * hanqr 2018-08-14
	 * @param deviceUpgradeId apk主键
	 * @param softVer mips版本号
	 * @param onlineStatus 在线状态(0:在线 1:离线)
	 * @param modelName 终端型号
	 * @param district 区
	 * @param pageNum 当前页
	 * @param pageSize 每页条数
	 * @param modelView 模型
	 * @return
	 */
	@RequestMapping(value = "/apkDeviceList")
	public String apkDeviceList(Long deviceUpgradeId,String softVer, Integer onlineStatus, String modelName, String district,
	                           Integer pageNum, Integer pageSize, Model modelView, HttpServletRequest request) {
		// 放入model，用户数据回显
		modelView.addAttribute("deviceUpgradeId", deviceUpgradeId);
		modelView.addAttribute("softVer", softVer);
		modelView.addAttribute("onlineStatus", onlineStatus);
		modelView.addAttribute("modelName", modelName);
		modelView.addAttribute("district", district);
		//登录用户信息
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		//登录用户城市编码
		String cityCode = loginUser.getCityCode();
		String cityName = loginUser.getCityName();
		List<AreaDistrictDTO> districtList = areaService.listDistrictByCityCode(cityCode);
		modelView.addAttribute("districtList", districtList);

		// mips版本号
		List<String> versionNameList = deviceInfoService.listAllSoftwareVersion();
		modelView.addAttribute("versionNameList", versionNameList);
		
		// 在线状态
		Map<Object, Object> onlineStatusMap = Maps.newHashMap();
		onlineStatusMap.put(BusinessConstant.DEVICE_INFO_STATUS_ON_LINE, "在线");
		onlineStatusMap.put(BusinessConstant.DEVICE_INFO_STATUS_OFF_LINE, "离线");
		modelView.addAttribute("onlineStatusMap", onlineStatusMap);
		
		// 机型
		List<DeviceModelDTO> deviceModelList = deviceModelService.listDeviceModelsSelectedUpgrade(deviceUpgradeId);
		modelView.addAttribute("deviceModelList", deviceModelList);

		if(StringUtils.isNotBlank(softVer)){
			softVer = softVer.replace("*", " ");
		}

		// apk-终端分页列表
		PageInfo<UpgradeDeviceListVO> pageInfo = deviceInfoService.listUpgradeDeviceByPage(cityName, softVer,null, onlineStatus, BusinessConstant.DEVICE_UPGRADE_TYPE_SOFTWARE, modelName, district, pageNum, pageSize);
		modelView.addAttribute("apkDeviceList", pageInfo.getList());
		modelView.addAttribute("total", pageInfo.getTotal());
		modelView.addAttribute("pageNum", pageInfo.getPageNum());
		modelView.addAttribute("pageSize", pageInfo.getPageSize());
		
		// 汇总在线、离线终端总数
		Long onlineCount = 0L;
		Long offlineCount = 0L;
		if ( null == onlineStatus ) {
			onlineCount = deviceInfoService.getDeviceCountByCondition(cityCode, BusinessConstant.DEVICE_INFO_STATUS_ON_LINE, softVer, null, modelName,
																		null, null, null, null, null, district, null);
			offlineCount = deviceInfoService.getDeviceCountByCondition(cityCode, BusinessConstant.DEVICE_INFO_STATUS_OFF_LINE, softVer, null, modelName,
					null, null, null, null, null, district, null);
		}else {
			// 查询条件筛选为在线终端，则在线终端数=所有终端数
			onlineCount = onlineStatus == BusinessConstant.DEVICE_INFO_STATUS_ON_LINE ? pageInfo.getTotal() : 0L;
			// 查询条件为离线终端，则离线终端数=所有终端数
			offlineCount = onlineStatus == BusinessConstant.DEVICE_INFO_STATUS_OFF_LINE ? pageInfo.getTotal() : 0L;
		}
		modelView.addAttribute("onlineCount", onlineCount);
		modelView.addAttribute("offlineCount",offlineCount);
		return "software_upgrade_device_list";
	}

	/**
	 * 更新mips
	 * hanqr 2018-08-14
	 * @param deviceCodes 终端唯一编码
	 * @param deviceUpgradeId apk主键
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateMips")
	public Object updateMips(String deviceCodes, Long deviceUpgradeId, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if (StringUtils.isBlank(deviceCodes)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL,"请选择终端");
		}
		if (deviceUpgradeId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL,"升级ID为空，请联系管理员");
		}
		try {
			deviceUpgradeService.deviceUpgrade(BusinessConstant.DEVICE_UPGRADE_TYPE_SOFTWARE,deviceCodes, deviceUpgradeId, user,HttpUtils.getRemortIP(request));
		} catch (Exception e) {
			logger.error("SoftwareUpgradeController updateMips 更新mips失败：" + e.getMessage(),e);
			return new JsonResponse(ResponseConstant.CODE_FAIL,"更新mips失败");
		}
		return "";
	}

	/**
	 * 删除升级记录，（如果该条记录未被终端升级设置关联的话）
	 * @param upgradeId 升级记录的主键id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/del", method = RequestMethod.POST)
	public Object delUpgradeRecord(Integer upgradeId) {
		if ( upgradeId == null ) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "请选择要删除的数据");
		}
		return deviceUpgradeService.del(upgradeId,null);
	}
}
